package com.seecen.webproject.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(
        initParams = {
                @WebInitParam(name = "username", value = "seecen"),
                @WebInitParam(name = "password", value = "123456")
        },
        urlPatterns = {
                "/hello"
                , "/hello2"
        },
        loadOnStartup = 1
)
public class UserController extends HttpServlet {

    public UserController() {
        System.out.println("执行了构造器");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        System.out.println("执行了init方法" + username + password);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 如果有中文，设置中文编码
        response.setCharacterEncoding("gbk");
        // 获取到用户发送过来的请求数据
        String keyword = request.getParameter("keyword");
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 响应结果给到浏览器
        response.getWriter().print("get Hello" + keyword);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 如果有中文，设置中文编码
        response.setCharacterEncoding("gbk");
        // 获取到用户发送过来的请求数据
        String keyword = request.getParameter("keyword");
        // 响应结果给到浏览器
        response.getWriter().print("post hello" + keyword);
    }

    public void destroy() {
        System.out.println("销毁了servlet实例");
    }
}
